package fr.insta.reverse.uml.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.insta.reverse.uml.service.ServiceFactory;
import fr.insta.reverse.uml.service.ServiceName;
import fr.insta.reverse.uml.service.ServiceProject;

public class ImageDisplayerController extends DefaultController
{

	public ImageDisplayerController(HttpServletRequest _request, HttpServletResponse _response)
	{
		super(_request, _response);
	}

	@Override
	public void execute() throws MalformedURLException
	{

		if (request.getParameter("idProject") != null)
		{
			ServiceProject serviceProjet = (ServiceProject) ServiceFactory.getService(ServiceName.ServiceProject);

			try
			{
				int idProject = Integer.parseInt(request.getParameter("idProject"));

				File imageProject = serviceProjet.getImageProject(idProject, request);

				InputStream input = new FileInputStream(imageProject);
				OutputStream output = response.getOutputStream();
				byte[] buffer = new byte[10240];

				try
				{
					for (int length = 0; (length = input.read(buffer)) > 0;)
						output.write(buffer, 0, length);
				}
				finally
				{
					try
					{
						output.close();
					}
					catch (IOException ignore)
					{
					}
					try
					{
						input.close();
					}
					catch (IOException ignore)
					{
					}
				}

			}
			catch (Exception _e)
			{
				return;
			}
		}
	}
}